package script;

import api.CommonApi;
import api.LoginApi;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import utils.AssertUtil;
import utils.ResponseData;
import utils.TestDataUtil;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;

public class TestLogin {
    private static final Logger logger = LoggerFactory.getLogger(TestLogin.class);

    private final LoginApi loginApi = new LoginApi();
    private final CommonApi commonApi = new CommonApi();

    @DataProvider

    public Object[][] buildData() throws IOException {
//        String s = FileUtils.readFileToString(new File("./data/login.json"), "UTF-8");
//        JSONArray jsonArray = JSONObject.parseArray(s);
//        Object[][] testData = new Object[jsonArray.size()][];
//        for (int i = 0; i < jsonArray.size(); i++) {
//            JSONObject jsonObject = jsonArray.getJSONObject(i);
//            testData[i] = new Object[]{jsonObject.getString("username"),
//                    jsonObject.getString("password"), jsonObject.getString("verifyCode"),
//                    jsonObject.getIntValue("code"), jsonObject.getString("description"),
//                    jsonObject.getIntValue("status")};
//        }
//        logger.info("testData={}", Arrays.deepToString(testData));
//        return testData;
        String keys = "username,password,verifyCode,code,description,status";
        Object[][] testData = TestDataUtil.buildData("login.json", keys);
        logger.info("testData={}",testData);
        return testData;

    }

    @Test(dataProvider = "buildData")
    public void testLog(String name, String password1, String verifyCode, int code, String description,
                        int status) throws Exception {
        //获取验证码
        commonApi.getVerifyCode(String.valueOf(new Random().nextDouble()));
        //登录
        ResponseData responseData = loginApi.login(name, password1, verifyCode);
//        //断言{"description":"OK","status":200}
//        Assert.assertEquals(responseData.getStatusCode(), code);
//        Assert.assertEquals(responseData.getBody().getString("description"), description);
//        Assert.assertEquals(responseData.getBody().getIntValue("status"), status);
        AssertUtil.commonAssert(responseData,code,description,status);


    }
}
